<?php

class UserController
{
    public function __construct()
    {
        if (isset($_GET["a"])) {
            $action = $_GET["a"];
            if ($action == "login") {
                $username = $_GET["username"];
                $password = $_GET["password"];
                //
                $user = $this->login($username, $password);
                if ($user) {
                    Utils::print(0, $user);
                } else {
                    Utils::print(1, "用户名或密码错误!");
                }
                return;
            }
            //
            if ($action == "regedit") {
                $username = $_GET["username"];
                $password = $_GET["password"];
                //
                $user = $this->regedit($username, $password);
                if ($user) {
                    Utils::print(0, $user);
                } else {
                    Utils::print(1, "用户名已注册!");
                }
                return;
            }
        }
    }

    public function login($username, $password)
    {
        $c = Connector::share()->reset();
        $t = $c->where("username", $username)->where("password", $password)->select("User");
        return $t->fetchObject();
    }

    public function regedit($username, $password)
    {
        $c = Connector::share()->reset();
        $t = $c->where("username", $username)->select("User");
        if ($t->fetchObject() == false){
            $model = [];
            $model["username"] = $username;
            $model["password"] = $password;
            if ($c->insert("User", $model) > 0) {
                $model["id"] = $c->getId();
                return $model;
            }
        }
        return false;
    }

    public function modify($model)
    {
        if (isset($model["id"])) {
            $c = Connector::share()->reset();
            $c->where("id", $model["id"]);
            if ($c->update("User", $model) > 0) {
                return true;
            }
        }
        return false;
    }

    public function delete($model)
    {
        if (isset($model["id"])) {
            $c = Connector::share()->reset();
            $c->where("id", $model["id"]);
            if ($c->delete("User") > 0) {
                return true;
            }
        }
        return false;
    }
}